import { computed, ref } from 'vue'
import { ComponentListItem, ComponentType, CustomFormTemplate } from './types'
import { useAddTemplate, useUpdateTemplateById } from './useTemplateList'
import { useGetDefaultComponetRow } from './useComponent'
import _ from 'lodash'
import { v4 as uuidv4 } from 'uuid'

// 单例模式
// 表单 - 内部使用 - 方便组件之间的传递值和修改值
const _form = ref<CustomFormTemplate>({
  id: '',
  name: '',
  status: true,
  createTime: '',
  updateTime: '',
  numberColumnOfEachRow: 4,
  componentList: [],
  processList: [
    {
      id: uuidv4(),
      nodes: [
        {
          id: uuidv4(),
          name: '工单登记',
          commanders: [],
          isStart: true,
          submit: false,
          isEnd: false,
          fieldPermissions: [],
        },
        {
          id: uuidv4(),
          name: '派单',
          commanders: [],
          isStart: false,
          submit: false,
          isEnd: false,
          fieldPermissions: [],
        },
        {
          id: uuidv4(),
          name: '结束流程',
          commanders: [],
          isStart: false,
          submit: false,
          isEnd: true,
          fieldPermissions: [],
        },
      ],
    },
  ],
})

/**
 * 模板表单
 */
export const useTemplateForm = () => {
  // 表单 - 外部使用
  const form = computed(() => {
    return _.cloneDeep(_form.value)
  })

  // 表单保存加载
  const formSaveLoading = ref(false)

  // 组件列表
  const componentList = computed(() => {
    return _.cloneDeep(_form.value.componentList)
  })

  // 组件列表 - 只有单行输入的 - 用于关联数据填充
  const inputComponentList = computed(() => {
    return _form.value.componentList.filter((component) => component.type === 'input')
  })

  const setComponentList = (componentList: Array<ComponentListItem>) => {
    _form.value.componentList = _.cloneDeep(componentList)
  }

  /**
   * 设置模板id
   * @param {string} newId - 新的id
   */
  const setFormId = (newId: string) => {
    _form.value.id = newId
  }

  /**
   * 设置模板名称
   * @param {string} newName - 新的模板名称
   */
  const setFormName = (newName: string) => {
    _form.value.name = newName
  }

  /**
   * 设置模板状态
   * @param {boolean} newStatus - 新的模板状态
   */
  const setFormStatus = (newStatus: boolean) => {
    _form.value.status = newStatus
  }

  /**
   * 设置模板创建时间
   * @param {string} newCreateTime - 新的模板创建时间
   */
  const setFormCreateTime = (newCreateTime: string) => {
    _form.value.createTime = newCreateTime
  }

  /**
   * 设置模板创建时间
   * @param {string} newUpdateTime - 新的模板更细时间
   */
  const setFormUpdateTime = (newUpdateTime: string) => {
    _form.value.updateTime = newUpdateTime
  }

  /**
   * 设置模板每行列数
   * @param {1|2|3|4} newRow - 每行列数
   */
  const setFormNumberColumnOfEachRow = (newRow: 1 | 2 | 3 | 4) => {
    _form.value.numberColumnOfEachRow = newRow
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    Object.assign(_form.value, {
      id: '',
      name: '',
      status: true,
      createTime: '',
      updateTime: '',
      numberColumnOfEachRow: 4,
      componentList: [],
    })
  }

  /**
   * 表单保存
   */
  const formSave = async () => {
    formSaveLoading.value = true
    if (_form.value.id) {
      await useUpdateTemplateById(_form.value)
    } else {
      _form.value.id = uuidv4()
      await useAddTemplate(_form.value)
    }
    formSaveLoading.value = false
  }

  /**
   * 添加组件
   * @param {ComponentType} type - 组件类型
   * @param {string} label - 标签
   */
  const addComponent = (type: ComponentType, beAssociated = false, label?: string) => {
    _form.value.componentList.push(useGetDefaultComponetRow(type, beAssociated, label))
  }

  /**
   * 根据序号更新组件列表
   * @param {ComponentListItem} component - 组件对象
   */
  const updateComponentListByComponent = (component?: ComponentListItem) => {
    if (component) {
      const index = _form.value.componentList.findIndex((item) => item.id === component.id)
      if (index >= 0) {
        _form.value.componentList[index] = _.cloneDeep(component)
      }
    }
  }

  /**
   * 更新组件的顺序
   * @param {number} sourceIndex - 源组件索引
   * @param {number} targetIndex - 目标组件索引
   */
  const swapComponentOrder = (sourceIndex: number, targetIndex: number) => {
    const targetComponent = _.cloneDeep(_form.value.componentList[targetIndex])
    const sourceComponent = _.cloneDeep(_form.value.componentList[sourceIndex])
    if (targetComponent && sourceComponent) {
      _form.value.componentList.splice(sourceIndex, 1)
      _form.value.componentList.splice(targetIndex, 0, sourceComponent)
    }
  }

  /**
   * 根据组件索引删除组件
   * @param {number} index - 组件索引
   */
  const delComponentByIndex = (index: number) => {
    const component = _form.value.componentList[index]
    if (component) {
      _form.value.componentList.splice(index, 1)
    }
  }

  /**
   * 根据组件序号查询组件对象
   * @param {string} id - 组件id
   */
  const findComponentById = (id: string) => {
    return componentList.value.find((component) => component.id === id)
  }

  /**
   * 根据子表单id获取子表单对应的所有单行输入组件对象
   * @param {string} id - 子表单id
   */
  const getChildFormInputComponentList = (id: string) => {
    const childForm = componentList.value.find((component) => component.id === id)
    if (childForm && childForm.type === 'child-form') {
      return childForm.childFormConfig.filter((config) => config.fieldType === 'input')
    }
    return null
  }

  return {
    form,
    componentList,
    formSaveLoading,
    inputComponentList,
    formSave,
    resetForm,
    setFormId,
    setFormName,
    addComponent,
    setFormStatus,
    setComponentList,
    setFormCreateTime,
    setFormUpdateTime,
    findComponentById,
    swapComponentOrder,
    delComponentByIndex,
    setFormNumberColumnOfEachRow,
    getChildFormInputComponentList,
    updateComponentListByComponent,
  }
}
